package com.CGFrame.struts.action;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.CGFrame.struts.bean.employee.EmployeeBean;

public class ShowExcelFromDatabaseAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HSSFWorkbook wb=new HSSFWorkbook();
		HSSFSheet sheet=wb.createSheet("雇员表");
		HSSFRow row=sheet.createRow(0);
		ArrayList list=EmployeeBean.getEmployees();
		
		//获得第一个元素来建立xls表头
		LinkedList firstEmployee=(LinkedList)list.get(0);
		short k=0;
		for(Iterator iter=firstEmployee.iterator();iter.hasNext();){
			HSSFCell cell=row.createCell(k);
			cell.setCellValue(new HSSFRichTextString((String)iter.next()));
			k++;
		}
		HSSFCellStyle style=wb.createCellStyle();
		style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
		for(int i=1;i<list.size();i++){
			LinkedList emp=(LinkedList)list.get(i);
			HSSFRow rows=sheet.createRow(i);
			int size=emp.size();
			for(int j=0;j<size;j++){
				Object o=emp.poll();
				HSSFCell cell=rows.createCell((short)j);
				if(o instanceof String){
					cell.setCellType(HSSFCell.CELL_TYPE_STRING);
					cell.setCellValue(new HSSFRichTextString((String)o));
				}else if(o instanceof Date){
					cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
					cell.setCellValue((Date)o);
					cell.setCellStyle(style);
				}
			}
		}
		
		String filePath=request.getSession().getServletContext().getRealPath("/雇员表.xls");
		FileOutputStream fos=new FileOutputStream(filePath);
		wb.write(fos);
		fos.close();

		request.setAttribute("workbook", wb);
		return mapping.findForward("excel");
	}
	
}
